package cqg.processor;

import java.util.Date;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;

import cqg.CqgReport;
import cqg.Provider;

/**
 * Implementation of Processor for FindBugs (http://findbugs.sourceforge.net).
 * <br><br>
 * @author Julio César Pérez Arques  
 * @see cqg.processor.Processor
 */
public class FindBugsProcessor extends XPathAbstractProcessor {
	public static final String PROVIDER_NAME = "FindBugs";
	private static final String ROOT_ELEMENT_NAME = "BugCollection";		
	
	@Override
	public String getRootElementName() {	
		return ROOT_ELEMENT_NAME;
	}
	
	protected CqgReport parseCqgReport(Document document, XPath xPath) throws XPathExpressionException {
		CqgReport cqgReport = new CqgReport();
		
		XPathExpression expr = null;
		expr = xPath.compile("count(//BugInstance[@priority='1'])");
		cqgReport.setCriticalFaultsCount(Integer.parseInt(expr.evaluate(document)));
		
		expr = xPath.compile("count(//BugInstance[@priority='2'])");
		cqgReport.setMajorFaultsCount(Integer.parseInt(expr.evaluate(document)));

		expr = xPath.compile("count(//BugInstance[@priority='3'])");
		cqgReport.setMinorFaultsCount(Integer.parseInt(expr.evaluate(document)));
		
		expr = xPath.compile("//@total_classes");
		cqgReport.setAnalyzedFilesCount(Integer.parseInt(expr.evaluate(document)));
		
		cqgReport.setDate(parseReportDate(document, xPath));
		
		Provider provider = parseProvider(document, xPath);
		cqgReport.setProvider(provider);
		
		return cqgReport;
	}
	
	private Provider parseProvider(Document document, XPath xPath) throws XPathExpressionException {
		Provider provider = new Provider();
		provider.setName(PROVIDER_NAME);
		
		XPathExpression expr = xPath.compile("//@version");
		provider.setVersion(expr.evaluate(document));
		
		return provider;
	}

	private Date parseReportDate(Document document, XPath xPath) throws XPathExpressionException {
		XPathExpression expr = xPath.compile("//@analysisTimestamp");
		String timestamp = expr.evaluate(document);
		long longDate = Long.parseLong(timestamp);
		Date date = new Date(longDate);
		return date;
	}
}
